package controller;

import model.Hobby;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.*;
import repository.HobbyRepository;
import repository.UserRepository;
import service.HobbyService;
import service.UserService;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("api/hobby")
@ComponentScan
public class HobbyController {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private HobbyRepository hobbyRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private HobbyService hobbyService;

    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    @ResponseBody
    public Hobby getHobbyById(@PathVariable("id") long id) {
        log.info("Get user by Id");
        return hobbyRepository.findOne(id);
    }

    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    @ResponseBody
    public Hobby updateHobby(@RequestBody final Hobby hobby) {
        log.info("Updating a hobby");
        return hobbyRepository.save(hobby);
    }

    @RequestMapping(value="", method=RequestMethod.POST)
    @ResponseBody
    public Hobby saveHobby(@RequestBody final Hobby hobby) {
        log.info("Saving a hobby");
        return hobbyRepository.save(hobby);
    }

    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public void deleteHobby(@PathVariable("id") long id) {
        log.info("Deleting a hobby");
        hobbyRepository.delete(id);
    }

    @RequestMapping(value="/hobbies/{idUser}", method=RequestMethod.GET)
    @ResponseBody
    public List<Hobby> getHobbiesByUser(@PathVariable(value="idUser") long idUser) {
        return hobbyRepository.getHobbiesByUser(idUser);
    }

    @RequestMapping(value="/save/list/{idUser}", method=RequestMethod.POST)
    public void saveHobbyList(@PathVariable(value="idUser") long idUser,
                              @RequestBody List<Hobby> hobbies) {

        hobbyService.saveHobbies(hobbies, userRepository.getOne(idUser));
    }

    @RequestMapping(value="/update/list/{idUser}", method=RequestMethod.PUT)
    public void updateHobbyList(@PathVariable(value="idUser") long idUser,
                              @RequestBody List<Hobby> hobbies) {

        hobbyService.updateHobbies(hobbies, userRepository.getOne(idUser));
    }
}